//先要加载 配置文件 config.js
require(['./config'], () => {
  //如果需要参数 要写到前面去
  require(['template', 'request', 'jquery', 'bootstrap'], (template, req) => {
    class Index {
      constructor() {
        this.load()
        this.fun()
        this.productData()
        this.prodImg()
        //这步应该处于页面加载完成之后
        // this.imgClick()
        this.createnavl()
        this.createnavr()
        this.inputChange()
        this.outClick()
        this.cartNum()
      }
      load() {
        document.body.parentNode.style.overflowX = "hidden";
      }
      fun() {
        // document.body.parentNode.style.overflowX = "hidden";
        var swiper = new Swiper('.swiper-container', {
          autoplay: true,
          spaceBetween: 200,
          effect: 'fade',
          loop: true,
          pagination: {
            el: '.swiper-pagination',
            clickable: true,
          },
          navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
          },
        });
      }
      inputChange() {
        $('.tsb_seachbox>.tsb_seachbox_input').on('input', function () {
          console.log($(this).val());
        })
      }
      //请求数据渲染页面 json 的方式
      // getProductData(){
      //   $.get('/lib/json/index_list.json',res=>{
      //     // console.log(res);
      //     // console.log(template)
      //     const html = template('productLists',{prodlist:res.result})
      //     console.log(html);
      //     $('#prouctsContent').html(html);
      //   })
      // }

      //官网复制的部分json数据
      productData() {
        req.getsProductData()
          .then(res => {
            // console.log(res)
            const html = template('productLists', {
              prodlist: res
            })
            // console.log(html);
            $('#prouctsContent').html(html);
          })
        //首页img的加载
      }
      prodImg() {
        $.post('/fn/sxtensionTheme', res => {
          const html = template('pi_imgs', {
            proImg: res
          })
          $('#pro_imgs').html(html);
        })
      }
      //渲染商品分类
      createnavl() {
        $.post('/fn/headMsg', res => {
          const li1List = res.typeThemeList
          let arr = []
          let a = 1
          li1List.map(item => {
            if (item.type === 1) {
              //控制id
              item.ts_id = 'tsblld_Y' + a
              a++
              arr.push(item)
            }
            return arr
          })
          // console.log(arr);
          const html = template('3C_nav', {
            a: arr
          })
          $('#tsbll_detail').html(html)
        })
      }
      createnavr() {
        $.post('/fn/headMsg', res => {
          const li1List = res.typeThemeList
          let arr = []
          let a = 1
          li1List.map(item => {
            if (item.type === 2) {
              //控制id
              item.ts_id = 'tsbtc_Z' + a
              a++
              arr.push(item)
            }
            return arr
          })
          const html = template('game_nav', {
            b: arr
          })
          $('#ttc_detail').html(html);
          this.picImgChang()
        })
        this.login()
        this.homeLogin()
        this.winScroll()
        this.picImgChang()
        this.searchName()
      }
      //监听用户登录
      login() {
        const a = document.cookie
        const user = a.split('=')[1]
        const loginBox = $('.tsb_login_box .tlb_to'),
          logOutBox = $('.tsb_login_box .tlb_new')
        if (user) {
          loginBox.css('display', 'none')
          logOutBox.css('display', 'block')
          $('.tlbn_username').text(user);
        } else {
          loginBox.css('display', 'block')
          logOutBox.css('display', 'none')
        }
      }
      //监听用户退出
      outClick() {
        $('.tlbno_out').on('click', function () {
          console.log('tuichu')
          //杀死cookie
          const cookie = document.cookie,
            username = cookie.split('=')[1]

          function setCookie(key, value, options = {
            expires: new Date(),
            path: '/'
          }) {
            document.cookie = `${key}=${encodeURIComponent(value)};expires=${options.expires};path=${options.path}`
          }
          setCookie('username', '', {
            expires: -1,
            path: '/'
          })
          const loginBox = $('.tsb_login_box .tlb_to'),
            logOutBox = $('.tsb_login_box .tlb_new')
          loginBox.css('display', 'block')
          logOutBox.css('display', 'none')
          const loname = $('.tsblb_username'),
            lopwd = $('.tsblb_password')
          loname.val('')
          lopwd.val('')
        })
      }
      //首页登录
      homeLogin() {
        let _that = this
        //获取账号和 密码的值
        const loname = $('.tsblb_username'),
          lopwd = $('.tsblb_password'),
          btn = $('.tsblb_login')
        let a = [JSON.parse(localStorage.getItem('usernameList'))]
        btn.on('click', function () {
          console.log(loname.val(), lopwd.val());
          if (loname.val() === '' || lopwd.val() === '') {
            alert('请输入正确密码!')
          } else {
            console.log('可以登录')
            if (a[0]) {
              let ss = []
              console.log(a)
              a.map(item => {
                item.map(item1 => {
                  if (item1.username === loname.val()) {
                    console.log('success');
                    ss.push(item1)
                    return ss
                  }
                })
              })
              if (ss[0]) {
                const flag = ss.some(item => {
                  return item.username === loname.val() && item.pwd === lopwd.val()
                })
                if (flag) {
                  function setCookie(key, value, options = {
                    expires: new Date(),
                    path: '/'
                  }) {
                    document.cookie = `${key}=${encodeURIComponent(value)};expires=${options.expires};path=${options.path}`
                  }
                  setCookie('username', loname.val(), {
                    path: '/',
                    expires: new Date('2020-12-20 00:00:00')
                  })
                  alert('登录成功！')
                  // window.location.href = `/index.html`
                  _that.login();
                } else {
                  alert('账号或者密码错误！')
                  loname.val('')
                  lopwd.val('')
                }
              } else {
                alert('请先注册！')
                window.location.href = '/html/register.html'
              }
            } else {
              alert('去注册！')
              window.location.href = '/html/register.html'
            }
          }
        })
      }
      //监听scroll
      winScroll() {
        let timer = setInterval(() => {
          $('header').css('display', 'block');
          if ($(document).scrollTop() >= 80) {
            //获取header
            $('header').css('display', 'none');
            $('.navv').css('position', 'fixed')
            $('.navv').css('zIndex', 99)
          } else {
            $('header').css('display', 'block');
            $('.navv').css('position', '')
          }
        }, 300)
      }
      //首页购物车的数量判断
      cartNum() {
        let a = $('.tsc_eee').text()
        const loginT = document.cookie
        const b = loginT.split('=')[1]
        if (b) {
          const userC = JSON.parse(localStorage.getItem('usernameList'))
          //这个是当前用户的信息
          let userCart = ''
          //通过filter 方法拿到当前的用户信息
          userC.filter(item => {
            if (item.username === b) {
              userCart = item
              return userCart
            }
          })
          $('.tsc_eee').text(`${userCart.cart.length}`)
        }else{
          $('.tsc_eee').text('0')
        }
      }
      //首页的图片
      picImgChang(){
        console.log($('.hplb_left'))
        let index = 0
        $('.hplb_left').click(function(){
          $(this).parent().find('.hplb_imgs').eq(index).fadeIn().siblings().fadeOut()
          index--
          if(index < 0){
            index = ($(this).parent().find('.hplb_imgs').length-1)
          }
        })
        $('.hplb_right').click(function(){
          index++
          $(this).parent().find('.hplb_imgs').eq(index).fadeIn().siblings().fadeOut()
          if(index >= ($(this).parent().find('.hplb_imgs').length-1)){
            index = 0
          }
        })

      }
      //tsb_search_btn
      searchName(){
        $('.tsb_search_btn').on('click',function(){
          let a = $('.tsb_seachbox_input').val()
          a = encodeURIComponent(a)
          window.location.href = `/html/search.html?name=${a}`
        })
      }
    }
    return new Index()
  })

})